
#! /usr/bin/python

import sys
import os
import time
import copy
import random
sys.path.append('../../../../')
from spade import *




class Example(Agent.Agent):
    def _setup(self):
        self.max=1
        self.setDefaultBehaviour(self.MainBehav())

    class MainBehav(Behaviour.OneShotBehaviour):


        def _process(self):
            list=self.myAgent.getOrganizationList()
            if not list:
                list=self.myAgent.getOrganizationList()
            create=True
            #check if the tourism organization has been created
            for o in list:
                if str(o)==str(self.myAgent.orgName):
                    create=False
            self.myAgent.org=MyFederation(agent=self.myAgent,nick=self.myAgent.nick,name=self.myAgent.orgName)
            #print "Soy "+self.myAgent.getAID().getName()+"y la creacion es "+str(create)
            if create:
                self.myAgent.createOrganization(self.myAgent.org)
                #o.setGoal({"ofrece":"informacion turistica","necesita":"fuentes de informacion turistica"})
                #unit creation
                self.myAgent.unit=MyFirstHierarchy(agent=self.myAgent, nick=self.myAgent.nick, name="supervision",password="pass",agentList=[])
                self.myAgent.org.addUnit(self.myAgent.unit)
                self.myAgent.team=MyTeam(agent=self.myAgent, nick=self.myAgent.nick)
                self.myAgent.org.joinSupervisorTeam(self.myAgent.team)
                #anwer request behaviour
                #mens=Behaviour.ACLTemplate()
                #mens.setPerformative("request")
                #mens.setOntology("Tourism")
                #t = Behaviour.MessageTemplate(mens)
                #b=self.BrokerBehaviour(u)
                #self.myAgent.addBehaviour(b,t)
                #b=self.PruebasBehaviour(u)
                #self.myAgent.addBehaviour(b)
            else:
                self.myAgent.joinOrganization(self.myAgent.org)
                if self.myAgent.tipo=="supervisor":
                    supervision=self.myAgent.org.requestSupervision()
                    while not supervision:
                          supervision=self.myAgent.org.requestSupervision()
                    self.myAgent.unit=MyHierarchy(agent=self.myAgent, nick=self.myAgent.nick, name=self.myAgent.unitName,password="pass",agentList=[])
                    self.myAgent.org.addUnit(self.myAgent.unit)
                    self.myAgent.team=MyTeam(agent=self.myAgent, nick=self.myAgent.nick)
                    self.myAgent.org.joinSupervisorTeam(self.myAgent.team)
                else:
                    print "agente jefe jerarquia"
                    entry=self.myAgent.org.requestEntryUnit(self.myAgent.divName)
                    while not entry:
                        entry=self.myAgent.org.requestEntryUnit(self.myAgent.divName)
                    print self.myAgent.divName
                    self.myAgent.unit=MyHierarchy(agent=self.myAgent, nick=self.myAgent.tipo, name=self.myAgent.divName,password=entry)
                    self.myAgent.org.joinUnit(self.myAgent.unit)
                    print "despues"
                    #l=o.getUnitList()
                #while not l:
                #  l=o.getUnitList()
                #d=o.requestDataForm(l[0])
                #while not d:
                #    d=o.requestDataForm(l[0])
                #d[0]["value"]="supervisor"
                #entry=o.requestEntryUnit(l[0],d)
                #if entry:
                #    u=Hierarchy(agent=self.myAgent,nick=self.myAgent.nick,name=l[0],password=entry)
                #    o.joinUnit(u)
                #    self.cont=1

"""        class BrokerBehaviour(Behaviour.Behaviour):
            def __init__(self,u):
                self.unit=u
                Behaviour.Behaviour.__init__(self)

            def _process(self):
                ans=self._receive(True,10)
                if ans:
                    #call to asking function
                    info=self.unit.askMembers(ans.getContent())
                    #answer message
                    mens=ACLMessage.ACLMessage()
                    mens.setPerformative("inform")
                    mens.setOntology("Tourism")
                    mens.setSender(self.myAgent.getAID())
                    mens.addReceiver(ans.getSender())
                    mens.setContent(str(info))
                    mens.setConversationId(ans.getConversationId())
                    self.myAgent.send(mens)
                time.sleep(0.5)


        class PruebasBehaviour(Behaviour.Behaviour):
            def __init__(self,u):
                self.unit=u
                Behaviour.Behaviour.__init__(self)

            def _process(self):
                fin=False
                mensajes={}
                list={}
                c=0
                while not fin:
                    #ver la estructura que la organizacion tiene en este momento
                    #print "Dentro de pruebas"
                    name="@"+self.myAgent.getAID().getName().split("@")[1]
                    units=self.unit.getUnitList()
                    #while not units:
                    #    units=self.unit.getUnitList()
                    #print units
                    p=self.unit.getMemberList()
                    mens=Behaviour.ACLTemplate()
                    mens.setPerformative("inform")
                    mens.setOntology("Pruebas")
                    id=random.randint(0,1000)
                    mens.setConversationId(id)
                    t = Behaviour.MessageTemplate(mens)
                    self.setTemplate(t)
                    #print units,p
                    old_list=list
                    list={}
                    for m in p:
                        list[m]="supervision"
                    #print list
                    for agent in units:
                        agent=agent+name
                        mens=ACLMessage.ACLMessage()
                        mens.setPerformative("request")
                        mens.setOntology("Pruebas")
                        mens.setSender(self.myAgent.getAID())
                        aid=AID.aid(agent,["xmpp://"+agent])
                        mens.addReceiver(aid)
                        mens.setContent(str(list))
                        mens.setConversationId(id)
                        self.myAgent.send(mens)
                    cont=0
                    while units!=[] and cont<5:
                        time.sleep(2)
                        ans=self._receive(True,10)
                        if not ans:
                            cont=cont+1
                        elif ans.getConversationId()==str(id):
                            l=eval(ans.getContent())
                            #print "Respuesta ",l
                            for k in l.keys():
                                if list[k]!=l[k] and l[k]!="supervision":
                                    list[k]=l[k]
                            units.remove(ans.getSender().getName().split("@")[0])
                    #print self.unit.getUnitList()
                    #print "Miembros",list
                    old_mensajes=mensajes
                    mensajes=self.numeroMensajes(list)
                    if old_mensajes==mensajes and list==old_list:
                        c=c+1
                    else:
                        c=0
                    if c>3:
                        fin=True
                    time.sleep(20)
                print "Fin"
                file = open('fin', 'w')
                file.write('prueba con exito')
                file.close()

            def numeroMensajes(self,est):
                nivel={"supervision":0}
                preguntas={"restaurant":"supervision","museo":"supervision","italiano":"restaurant","chino":"restaurant","japones":"restaurant","buffet":"italiano","menu":"italiano","vegetariano":"chino","normal":"chino","centrico":"japones","afueras":"japones","pintura":"museo","artemoderno":"museo","escultura":"museo"}
                cont=len(est.keys())
                for k in est.keys():
                    if est[k] not in nivel.keys():
                        nivel[est[k]]=1
                        cont=cont-1
                    else:
                        nivel[est[k]]=nivel[est[k]]+1
                #print nivel
                mensajes={}
                for k in preguntas.keys():
                    ini=k
                    mensajes[k]=0
                    while ini not in nivel.keys():
                        ini=preguntas[ini]
                    #print ini
                    mensajes[k]=nivel[ini]
                    if ini!="supervision":
                        ini=preguntas[ini]
                        while ini!="supervision":
                            mensajes[k]=mensajes[k]+nivel[ini]
                            ini=preguntas[ini]
                        mensajes[k]=mensajes[k]+nivel[ini]

                print "Estructura -> ",est
                print "Agentes -> ",cont
                print "Mensajes -> ",mensajes
                return mensajes

"""

class MyFederation(Organization.Federation):
    def onStart(self):
        self.supervisores=[]
    def _process(self):
        time.sleep(2000)
    def supervisionTest(self,sender,desc=None):
        if sender in self.supervisores:
            return True
        return False

class MyFirstHierarchy(Unit.Hierarchy):
    def onStart(self):
        self.divisiones=[]
    def _process(self):
        units=self.myAgent.org.getUnitList()
        mens=ACLMessage.ACLMessage()
        mens.setPerformative("request")
        mens.setContent("Division")
        self.sendMessage(mens)
        ans=self.receiveMessage()
        while ans:
            if ans.getPerformative()=="inform" and "Division:" in ans.getContent():
                div=ans.getContent().split("Division:")[1]
                if div not in self.divisiones:
                    self.myAgent.addBehaviour(self.AddSupervisorBehaviour(div))
                elif div in units:
                    self.myAgent.addBehaviour(SendGotoBehaviour(ans.getSender(),div))
            ans=self.receiveMessage()
    def entryUnitTest(self,sender,desc=None):
        return True

    class AddSupervisorBehaviour(Behaviour.OneShotBehaviour):
        def __init__(self,division):
            self.division=division
            Behaviour.OneShotBehaviour.__init__(self)
        def _process(self):
            self.myAgent.unit.divisiones.append(self.division)
            #creamos el agente encargado de la nueva division
            agent=self.division+"@"+self.myAgent.getAID().getName().split("@")[1]
            b = Example(agent,"p")
            b.unitName=self.division
            b.orgName=self.myAgent.orgName
            b.nick=self.division
            b.tipo="supervisor"
            b.start()
            self.myAgent.org.supervisores.append(agent)

class SendGotoBehaviour(Behaviour.OneShotBehaviour):
        def __init__(self,agent,to):
            self.agent=agent
            self.to=to
            Behaviour.OneShotBehaviour.__init__(self)

        def _process(self):
            #print "Pa la unidad ",self.to,self.agent,self.myAgent.unit.name,self.myAgent.team.name
            mens=ACLMessage.ACLMessage()
            mens.setPerformative("inform")
            mens.setSender(self.myAgent.getAID())
            mens.setContent("Goto:"+self.to)
            men=ACLMessage.ACLMessage()
            men.setPerformative("inform")
            men.setSender(self.myAgent.getAID())
            men.setContent(str({"Agent":self.agent.getName(),"Unit":self.to}))
            cont=0
            t=0.5
            #print mens
            while cont<15:
                cont=cont+1
                self.myAgent.unit.sendPrivateMessage(mens,self.agent.getName())
                self.myAgent.team.sendMessage(men)
                time.sleep(t)
                t=t+0.5

class MyTeam(Unit.Team):
    def _process(self):
        m=self.receiveMessage()
        if m:
            if m.getPerformative()=="inform":
                d=eval(m.getContent())
                unit=d["Unit"]
                agent=d["Agent"]
                if unit==self.myAgent.unit.name:
                    self.myAgent.unit.agents.append(agent)

class MyHierarchy(Unit.Hierarchy):
    def onStart(self):
            self.agents=[]
            self.types=[]
            self.supervisores=[]
    def entryUnitTest(self,sender,desc=None):
        if sender in self.agents or sender in self.supervisores:
            return True
        return False
    def supervisionTest(self,sender,desc=None):
        print sender
        if sender in self.supervisores:
            return True
        return False
    def _process(self):
        if self.owner==True:
            if self.getNumberOfAgents()>self.myAgent.max:
                units=self.getUnitList()
                mens=ACLMessage.ACLMessage()
                mens.setPerformative("request")
                mens.setContent("Type")
                self.sendMessage(mens)
                ans=self.receiveMessage()
                while ans:
                    if ans.getPerformative()=="inform" and "Type:" in ans.getContent():
                        type=ans.getContent().split("Type:")[1]
                        if type not in self.types and type!=self.name:
                            self.myAgent.addBehaviour(self.AddHierarchySupervisorBehaviour(type))
                        elif type in units:
                            self.myAgent.addBehaviour(SendGotoBehaviour(ans.getSender(),type))
                    ans=self.receiveMessage()
        else:
            print "Dentro de la jerarquia"
            supervision=self.requestSupervision()
            while not supervision:
                supervision=self.requestSupervision()
            self.myAgent.unit=MyHierarchy(agent=self.myAgent, nick=self.myAgent.nick, name=self.myAgent.unitName,password="pass",agentList=[])
            self.addUnit(self.myAgent.unit)


    class AddHierarchySupervisorBehaviour(Behaviour.OneShotBehaviour):
        def __init__(self,division):
            self.division=division
            Behaviour.OneShotBehaviour.__init__(self)
        def _process(self):
            self.myAgent.unit.types.append(self.division)
            #creamos el agente encargado de la nueva division
            agent=self.division+"@"+self.myAgent.getAID().getName().split("@")[1]
            b = Example(agent,"p")
            b.unitName=self.division
            b.orgName=self.myAgent.orgName
            b.divName=self.myAgent.unitName
            b.nick=self.division
            b.tipo="hierarchySupervisor"
            b.start()
            self.myAgent.unit.supervisores.append(str(agent))

            """
    def onStart(self):
        if self.owner==True:
            self.setGoal({"necesita":"fuentes de informacion"})
            self.addDataFormItem(name="rol",desc="rol que asume el agente")
            self.addDataFormItem(name="tipo",desc="lista con el tipo de agente")
            self.delegate=False
            self.subunits=[]
            self.fuentes=[]
            self.supervisores=[]
            self.gotolist=[]
            self.max=self.myAgent.max
            self.div=self.myAgent.div
            template = Behaviour.ACLTemplate()
            template.setProperty("from",self.name)
            template.setPerformative("inform")
            template.setOntology("spade:x:unit")
            t = Behaviour.MessageTemplate(template)
            self.addMemberBehaviour=self.AddMemberBehaviour(self)
            self.myAgent.addBehaviour(self.addMemberBehaviour, t)

        else:
            d=[{"value":"supervisor","name":"rol"},{"value":self.myAgent.div,"name":"nivel"}]
            self.myAgent.cont=self.myAgent.cont+1
            creation=self.requestCreationPermission(d)
            #print "PERMISO CREACION ",self.myAgent.getAID().getName()," sala",self.name," creacion:",creation," cont ",self.myAgent.cont," list ",self.myAgent.list
            while not creation and self.myAgent.cont==len(self.myAgent.list):
                creation=self.requestCreationPermission(d)
                #print "PERMISO CREACION ",self.myAgent.getAID().getName()," sala",self.name," creacion:",creation
            #asking for creation permision
            if creation:
                u=Hierarchy(agent=self.myAgent, nick=self.myAgent.nick, name=self.myAgent.unit,password="pass",agentList=["sitea@apolo.dsic.upv.es"])
                self.addUnit(u)
                mens=Behaviour.ACLTemplate()
                mens.setPerformative("request")
                #mens.setOntology("Tourism")
                mens.setOntology("Pruebas")
                t = Behaviour.MessageTemplate(mens)
                #b=self.BrokerBehaviour(self,u)
                b=self.PruebasBehaviour(u)
                self.myAgent.addBehaviour(b,t)
            else:
                #entering existing unit
                #print "Contador ",self.myAgent.cont," Lista ",self.myAgent.list
                unit=self.myAgent.list[self.myAgent.cont]
                #print "Tratando de entrar a "+unit,self.myAgent.list
                d=self.requestDataForm(unit)
                while not d:
                    d=self.requestDataForm(unit)
                d[0]["value"]="supervisor"
                entry=self.requestEntryUnit(unit,d)
                if not entry:
                    entry=self.requestEntryUnit(unit,d)
                #print "Soy "+self.myAgent.getAID().getName()+" y la respuesta de entrada a "+unit+" es "+str(entry)
                if entry:
                    u=Hierarchy(agent=self.myAgent,nick=self.myAgent.nick,name=unit,password=entry)
                    self.joinUnit(u)

    class BrokerBehaviour(Behaviour.Behaviour):
        def __init__(self,currentUnit,unit):
            self.currentUnit=currentUnit
            self.unit=unit
            Behaviour.Behaviour.__init__(self)

        def _process(self):
            #reciving message from the current unit
            ans=self.currentUnit.receiveMessage()
            info=""
            if ans:
                #asking memebers of the sub unit
                aux=copy.copy(self.myAgent.list)
                aux.reverse()
                aux.pop()
                aux.reverse()
                t=""
                for i in aux:
                    t=t+str(i).lower()+":"
                t=t+str(self.myAgent.nick)
                #print "Soy:",self.myAgent.getAID().getName()," mi informacion es ",t," me preguntan",ans.getContent().lower()
                if ans.getContent().lower() in t or t in ans.getContent().lower():
                    info=self.unit.askMembers(ans.getContent())
                mens=ACLMessage.ACLMessage()
                mens.setPerformative("inform")
                mens.setOntology("Restaurant")
                mens.setSender(self.myAgent.getAID())
                mens.addReceiver(ans.getSender())
                mens.setContent(str(info))
                mens.setConversationId(ans.getConversationId())
                self.currentUnit.sendPrivateMessage(mens,ans.getSender().getName())
                time.sleep(0.5)

    class PruebasBehaviour(Behaviour.Behaviour):
        def __init__(self,u):
                self.unit=u
                Behaviour.Behaviour.__init__(self)

        def _process(self):
            ans=self._receive(True,10)
            while not ans:
                time.sleep(0.5)
                ans=self._receive(True,10)
            mens=Behaviour.ACLTemplate()
            mens.setPerformative("inform")
            mens.setOntology("Pruebas")
            t = Behaviour.MessageTemplate(mens)
            id=random.randint(0,1000)
            b=self.ConsultaBehaviour(self.unit,ans,id)
            self.myAgent.addBehaviour(b,t)
            #print "Mensaje recibido",ans

        class ConsultaBehaviour(Behaviour.OneShotBehaviour):
            def __init__(self,u,ans,id):
                    self.unit=u
                    self.ans=ans
                    self.id=id
                    Behaviour.OneShotBehaviour.__init__(self)

            def _process(self):
                name="@"+self.myAgent.getAID().getName().split("@")[1]
                units=self.unit.getUnitList()
                p=self.unit.getMemberList()
                #print p,units,self.unit.name
                list=eval(self.ans.getContent())
                for agent in list.keys():
                    if agent in p:
                        list[agent]=self.unit.name
                for agent in units:
                    mens=ACLMessage.ACLMessage()
                    mens.setPerformative("request")
                    mens.setOntology("Pruebas")
                    mens.setSender(self.myAgent.getAID())
                    aid=AID.aid(agent+name,["xmpp://"+agent+name])
                    mens.addReceiver(aid)
                    mens.setContent(str(list))
                    mens.setConversationId(self.id)
                    #print "Soy",self.myAgent.getAID().getName(),"Envio a ",agent," ",mens
                    self.myAgent.send(mens)
                cont=0
                while units!=[] and cont<5:
                    time.sleep(2)
                    a=self._receive(True,10)
                    if not a:
                        cont=cont+1
                    else:
                        #print "Recibo de ",a.getSender().getName().split("@")[0],"->",a
                        if a.getConversationId()==str(self.id):
                            l=eval(a.getContent())
                            #print "Recibo de ",a.getSender().getName().split("@")[0],"->",l
                            for agent in l.keys():
                                if l[agent]!=list[agent] and l[agent]!=self.unit.name:
                                    list[agent]=l[agent]
                            units.remove(a.getSender().getName().split("@")[0])
                mens=ACLMessage.ACLMessage()
                mens.setPerformative("inform")
                mens.setOntology("Pruebas")
                mens.setSender(self.myAgent.getAID())
                mens.addReceiver(self.ans.getSender())
                mens.setContent(str(list))
                mens.setConversationId(self.ans.getConversationId())
                self.myAgent.send(mens)
                #print "Soy",self.myAgent.getAID().getName(),"Envio a ",self.ans.getSender().getName()," ",mens
                #print "Mensaje enviado ",mens

    def _process(self):
        if self.owner==True:
            div=self.myAgent.div
            if len(self.fuentes)>self.max:
                    #contador para cada tipo de agentes
                    cont={}
                    for f in self.fuentes:
                        if div<len(f["tipo"]) and f["tipo"][div] not in self.subunits:
                            if not cont.has_key(f["tipo"][div]):
                                cont[f["tipo"][div]]=1
                            else:
                                cont[f["tipo"][div]]=1+cont[f["tipo"][div]]
                    max=0
                    tmax=""
                    #selecionamos el maximo
                    for k in cont.keys():
                        if int(cont[k])>max:
                            max=cont[k]
                            tmax=k
                    if max>0 and tmax!="":
                        agent=str(tmax)
                        agent=agent+"@"+self.myAgent.getAID().getName().split("@")[1]
                        b = Example(agent,"p")
                        b.orgName="turismo"
                        b.nick=str(tmax)
                        b.unit=tmax
                        b.max=self.myAgent.max
                        b.div=self.div+1
                        b.list=copy.copy(self.myAgent.list)
                        b.list.append(self.name)
                        #print agent,b.list
                        b.cont=0
                        #print "Creando al agente ",agent
                        b.start()
                        #anyadimos la nueva unidad que se va a crear
                        self.subunits.append(tmax)

            units=self.getUnitList()
            agents=[]
            for f in self.fuentes:
                if div<len(f["tipo"]) and f["tipo"][div] in units:
                    agents.append(f)
            for a in agents:
                #print "Enviando a "+a["name"]+" a la unidad "+a["tipo"][div]
                m=a["name"]
                unit=a["tipo"][div]
                supervisor=unit+"@"+self.myAgent.getAID().getName().split("@")[1]
                self.fuentes.remove(a)
                self.sendGoto(m,unit)
                #self.sendAddMember(supervisor,m,unit)

        time.sleep(0.1)

    def entryUnitTest(self,sender,desc=None):
      tipo=""
      subtipo=""
      for l in desc:
          if l["name"]=="rol":
              rol=str(l["value"])
          elif l["name"]=="tipo":
              if l["value"]!="":
                  aux=[]
                  for i in l["value"]:
                      aux.append(i.lower())
                  tipo=aux
      if rol=="fuentes de informacion":
               if sender not in self.fuentes:
                   self.fuentes.append({"name":sender,"tipo":tipo})
                   #print "El agente ",sender," datos ",tipo," entra a la unidad"
               return True
      if rol=="supervisor":
               if sender not in self.supervisores:
                   self.supervisores.append(sender)
               return True
      return False

    def creationPermissionTest(self,sender,desc=None):
        #print "Asking for creation:",sender,"->",desc
        for l in desc:
          if l["name"]=="rol":
              rol=str(l["value"])
          elif l["name"]=="nivel":
              nivel=str(l["value"])
        if rol=="supervisor" and int(nivel)==self.div+1:
            self.supervisores.append(sender)
            return True
        return False

    def sendGoto(self,agent,unit):
        self.myAgent.addBehaviour(self.SendGotoBehaviour(agent,unit,self.name))


    class SendGotoBehaviour(Behaviour.OneShotBehaviour):
        def __init__(self,agent,unit,name):
            self.agent=agent
            self.unit=unit
            self.name=name
            Behaviour.OneShotBehaviour.__init__(self)

        def _process(self):
            mens=ACLMessage.ACLMessage()
            mens.setPerformative("inform")
            mens.setOntology("spade:x:unit")
            mens.setSender(self.myAgent.getAID())
            aid=AID.aid(agent,["xmpp://"+self.agent])
            mens.addReceiver(aid)
            mens.setContent("Goto:"+self.unit)
            mens.setProperty("from",self.name)
            cont=0
            t=0.5
            while cont<15:
                cont=cont+1
                self.myAgent.send(mens)
                time.sleep(t)
                t=t+0.5

    def sendAddMember(self,manager,member,unit):
        self.myAgent.addBehaviour(self.SendAddMemberBehaviour(manager,member,unit))


    class SendAddMemberBehaviour(Behaviour.OneShotBehaviour):
        def __init__(self,manager,member,unit):
            self.manager=manager
            self.unit=unit
            self.member=member
            Behaviour.OneShotBehaviour.__init__(self)

        def _process(self):
            mens=ACLMessage.ACLMessage()
            mens.setPerformative("inform")
            mens.setOntology("spade:x:unit")
            mens.setSender(self.myAgent.getAID())
            aid=AID.aid(manager,["xmpp://"+self.manager])
            mens.addReceiver(aid)
            mens.setContent("Member:"+self.member)
            mens.setProperty("from",self.unit)
            cont=0
            while cont<5:
                cont=cont+1
                self.myAgent.send(mens)
                time.sleep(0.5)

    class AddMemberBehaviour(Behaviour.Behaviour):
        def __init__(self,unit):
            self.unit=unit
            Behaviour.Behaviour.__init__(self)

        def _process(self):
            m= self._receive(True)
            if m and m.getProperty("from")==self.unit.name:
                if m.getContent().split(":")[0]=="Member":
                    agent=m.getContent().split(":")[1]
                    self.unit.addMember(agent)

    def askMembers(self,about):
        mens=ACLMessage.ACLMessage()
        mens.setPerformative("request")
        mens.setSender(b.getAID())
        mens.setOntology("Restaurant")
        mens.setContent(about)
        id=random.randint(0,1000)
        mens.setConversationId(id)
        self.sendMessage(mens)
        niveles=self.niveles()
        if niveles<=0:
            niveles=self.niveles()
        #el problema esta en que el numero de agentes maximo no es representativo del tamanyo hay q esperar a que los brokers contesten
        espera=(2*self.max)*int(niveles-self.myAgent.div)
        if espera<0:
            #print "Espera es menor que 0",espera,niveles,self.myAgent.div
            espera=10
        num=int(self.getNumberOfAgents())-1
        list=[]
        agents=[]
        cont=1
        nans=0
        #print "Soy ",self.myAgent.getAID().getName()," los agentes de la unidad son ",self.getMemberList()
        while cont<4 and num>0:
            print "Soy "+self.myAgent.getAID().getName()+" espero un poco mas"+str(int(espera/cont))
            time.sleep(int(espera/cont))
            ans=self.receiveMessage()
            while ans:
                if ans and ans.getPerformative()=="inform" and ans.getConversationId()==str(id):
                    num=num-1
                    if ans.getContent()!="":
                        print "Recibido de",ans.getSender().getName(),"->",ans.getContent()
                        d={"jid":str(ans.getSender().getName()),"info":eval(ans.getContent())}
                        if eval(ans.getContent()).__class__==dict and eval(ans.getContent()).has_key("cont"):
                            nans=eval(ans.getContent())["cont"]+nans
                        list=list+[d]
                    agents=agents+[str(ans.getSender().getName())]
                ans=self.receiveMessage()
            cont=cont+1
        print "Soy "+self.myAgent.getAID().getName()+" y tengo las respuestas de "+str(agents)
        if list==[]:list=""
        nans=nans+len(agents)
        return {"info":list,"cont":nans,"jid":self.myAgent.getAID().getName()}

    def niveles(self):
        cont=0
        name=self.parent.strip(":")[0]
        dad = DF.DfAgentDescription()
        ds = DF.ServiceDescription()
        ds.setType("UNIT")
        dad.addService(ds)
        search = self.myAgent.searchService(dad)
        if search:
          for d in search:
                  for s in d.getServices():
                          prop=s.getProperties()
                          for p in prop:
                              if p["name"].strip("u'")=="parent" and name in p["value"].strip("u'"):
                                  cont=cont+1
        return cont

"""
if __name__ == "__main__":
    agent = "broker@apolo.dsic.upv.es"

    b = Example(agent,"pasword")
    b.unitName=""
    b.orgName="turismo"
    b.nick="supervisor"
    b.start()





